package com.example.labb2da523b.db;

import java.sql.SQLException;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


public class SqlHelper {
	private static Context context;
	private DatabaseHelper DBHelper;
	private SQLiteDatabase db;

	public SqlHelper(Context ctx){
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}
	public SqlHelper open() throws SQLException{
		db = DBHelper.getWritableDatabase();
		return this;
	}
	public void close(){
		DBHelper.close();
	}
	public long insertBudget(Integer budget){
		ContentValues initialValues = new ContentValues();
		initialValues.put(DatabaseHelper.KEY_BUDGET, budget);
		return db.insert(DatabaseHelper.USER_TABLE_NAME, null, initialValues);
	}
	public int getBudget(){
		int budget = 0;
		Cursor cursor = db.query(DatabaseHelper.USER_TABLE_NAME,
				new String[]{DatabaseHelper.KEY_BUDGET}, null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			budget = cursor.getInt(0);
			cursor.moveToNext();
		}
		cursor.close();
		return budget;
	}
	public long insertExpense(Expense newExpense){
		ContentValues initialValues = new ContentValues();
		initialValues.put(DatabaseHelper.KEY_SUM, newExpense.getSum());
		initialValues.put(DatabaseHelper.KEY_CATEGORY, newExpense.getCategory());
		initialValues.put(DatabaseHelper.KEY_DATE, newExpense.getDate());
		initialValues.put(DatabaseHelper.KEY_EXPENSE_NAME, newExpense.getName());
		return db.insert(DatabaseHelper.EXPENSE_TABLE_NAME, null, initialValues);
	}

	public ArrayList<Expense> getAllExpenses() {
		Expense expense;
		ArrayList<Expense> expenses = new ArrayList<Expense>();

		Cursor cursor = db.query(DatabaseHelper.EXPENSE_TABLE_NAME,
				DatabaseHelper.allExpenseColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			expense = new Expense();
			expense.setId(cursor.getInt(0));
			expense.setCategory(cursor.getString(2));
			expense.setDate(cursor.getString(3));
			expense.setName(cursor.getString(4));
			expense.setSum(cursor.getInt(1));
			expenses.add(expense);
			cursor.moveToNext();
		}
		cursor.close();
		return expenses;
	}
}